import json

import pyperclip
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models
import base64


class FormulaRecognition:
    def __init__(self, secretId, secretKey, img_path):
        self.SecretId = secretId
        self.SecretKey = secretKey
        self.img_path = img_path

    def imgBaes64(self):
        with open(self.img_path, 'rb') as f:
            image_data = f.read()
            self.base64_data = base64.b64encode(image_data)
            self.base64_data = str(self.base64_data, 'utf-8')

    def runOCR(self):
        self.imgBaes64()
        try:
            cred = credential.Credential(self.SecretId, self.SecretKey)
            # 实例化一个http选项，可选的，没有特殊需求可以跳过
            httpProfile = HttpProfile()
            httpProfile.endpoint = "ocr.tencentcloudapi.com"

            # 实例化一个client选项，可选的，没有特殊需求可以跳过
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            # 实例化要请求产品的client对象,clientProfile是可选的
            client = ocr_client.OcrClient(cred, "ap-shanghai", clientProfile)

            # 实例化一个请求对象,每个接口都会对应一个request对象
            req = models.FormulaOCRRequest()
            params = {
                "ImageBase64": self.base64_data
            }
            req.from_json_string(json.dumps(params))

            # 返回的resp是一个FormulaOCRResponse的实例，与请求对象对应
            resp = client.FormulaOCR(req)
            # 输出json格式的字符串回包
            a = json.loads(resp.to_json_string())
            result = a["FormulaInfos"][0]["DetectedText"]
            pyperclip.copy(result)

        except TencentCloudSDKException as err:
            pyperclip.copy(err)
